package com.lagou.edu.pojo;

import com.lagou.edu.util.HttpProtocolUtil;
import com.lagou.edu.util.ResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @ClassName: Response
 * @Auther: Jerry
 * @Date: 2020/7/30 23:51
 * @Desctiption: TODO
 * @Version: 1.0
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    /**
     * 根据输出流构建Response对象
     * @param outputStream 输出流
     */
    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 输出内容
     * @param content 内容
     */
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    /**
     * 根据请求路径输出Html
     * @param path 路径
     */
    public void outputHtml(String path) throws IOException {
        // 根据路径获取绝对路径
        String absolutePath = ResourceUtil.getAbsolutePath(path);
        // 判断文件是否存在
        File file = new File(absolutePath);
        // 如果资源存在，则输出返回，如果不存在则返回404
        if (file.exists() && file.isFile()) {
            ResourceUtil.outputResource(new FileInputStream(file), outputStream);
        } else {
            output(HttpProtocolUtil.getHeader404());
        }

    }


    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }
}
